<template>
  <div class="register-container">
    <el-card class="register-box">
      <template #header>
        <div class="card-header">
          <h2>注册账号</h2>
          <el-tabs v-model="registerType" class="register-tabs">
            <el-tab-pane label="手机号注册" name="phone">
              <el-form
                ref="registerFormRef"
                :model="registerForm"
                :rules="rules"
                label-position="top"
                @submit.prevent="handleRegister"
              >
                <el-form-item prop="account" label="手机号">
                  <el-input
                    v-model="registerForm.account"
                    placeholder="请输入手机号"
                    :prefix-icon="Phone"
                  />
                </el-form-item>
                <el-form-item prop="verificationCode" label="验证码">
                  <div class="verification-group">
                    <el-input
                      v-model="registerForm.verificationCode"
                      placeholder="请输入验证码"
                      :prefix-icon="Key"
                    />
                    <el-button
                      type="primary"
                      :disabled="isCountingDown"
                      @click="sendVerificationCode"
                    >
                      {{ countDownText }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                  <el-input
                    v-model="registerForm.password"
                    type="password"
                    placeholder="请设置密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>
                <el-form-item prop="confirmPassword" label="确认密码">
                  <el-input
                    v-model="registerForm.confirmPassword"
                    type="password"
                    placeholder="请确认密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="agreedToTerms">
                    我已阅读并同意
                    <el-link type="primary" :underline="false">
                      <router-link to="/terms">《用户协议》</router-link>
                    </el-link>
                    和
                    <el-link type="primary" :underline="false">
                      <router-link to="/privacy">《隐私政策》</router-link>
                    </el-link>
                  </el-checkbox>
                </el-form-item>
                <el-button
                  type="primary"
                  native-type="submit"
                  :loading="isLoading"
                  :disabled="!agreedToTerms"
                  class="submit-btn"
                >
                  {{ isLoading ? '注册中...' : '注册' }}
                </el-button>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="邮箱注册" name="email">
              <el-form
                ref="emailFormRef"
                :model="registerForm"
                :rules="emailRules"
                label-position="top"
                @submit.prevent="handleRegister"
              >
                <el-form-item prop="account" label="邮箱">
                  <el-input
                    v-model="registerForm.account"
                    placeholder="请输入邮箱"
                    :prefix-icon="Message"
                  />
                </el-form-item>
                <el-form-item prop="verificationCode" label="验证码">
                  <div class="verification-group">
                    <el-input
                      v-model="registerForm.verificationCode"
                      placeholder="请输入验证码"
                      :prefix-icon="Key"
                    />
                    <el-button
                      type="primary"
                      :disabled="isCountingDown"
                      @click="sendVerificationCode"
                    >
                      {{ countDownText }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                  <el-input
                    v-model="registerForm.password"
                    type="password"
                    placeholder="请设置密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>
                <el-form-item prop="confirmPassword" label="确认密码">
                  <el-input
                    v-model="registerForm.confirmPassword"
                    type="password"
                    placeholder="请确认密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="agreedToTerms">
                    我已阅读并同意
                    <el-link type="primary" :underline="false">
                      <router-link to="/terms">《用户协议》</router-link>
                    </el-link>
                    和
                    <el-link type="primary" :underline="false">
                      <router-link to="/privacy">《隐私政策》</router-link>
                    </el-link>
                  </el-checkbox>
                </el-form-item>
                <el-button
                  type="primary"
                  native-type="submit"
                  :loading="isLoading"
                  :disabled="!agreedToTerms"
                  class="submit-btn"
                >
                  {{ isLoading ? '注册中...' : '注册' }}
                </el-button>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <div class="login-link">
        已有账号？
        <el-link type="primary" :underline="false">
          <router-link to="/login">立即登录</router-link>
        </el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Phone, Message, Key, Lock } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const router = useRouter()
const registerType = ref('phone')
const isLoading = ref(false)
const agreedToTerms = ref(false)
const countdown = ref(0)
const registerFormRef = ref<FormInstance>()
const emailFormRef = ref<FormInstance>()

const registerForm = reactive({
  account: '',
  verificationCode: '',
  password: '',
  confirmPassword: ''
})

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      if (registerFormRef.value) {
        registerFormRef.value.validateField('confirmPassword')
      }
    }
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
})

const emailRules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
})

const isCountingDown = computed(() => countdown.value > 0)
const countDownText = computed(() => 
  isCountingDown.value ? `${countdown.value}秒后重试` : '获取验证码'
)

const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const sendVerificationCode = async () => {
  try {
    // TODO: 实现发送验证码逻辑
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    startCountdown()
    ElMessage.success('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送验证码失败')
  }
}

const handleRegister = async () => {
  const formRef = registerType.value === 'phone' ? registerFormRef : emailFormRef
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    isLoading.value = true
    // TODO: 实现注册逻辑
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    ElMessage.success('注册成功')
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败')
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 80px);
  background-color: #f5f5f5;
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 480px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 20px;
  color: #2c3e50;
  font-size: 24px;
}

.register-tabs {
  margin-bottom: 20px;
}

.verification-group {
  display: flex;
  gap: 10px;
}

.verification-group .el-button {
  width: 120px;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

:deep(.el-tabs__nav) {
  width: 100%;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 